package com.thinkgem.jeesite.common.utils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class HttpClientUtil {

    /**
     * 发送get请求
     * 
     * @param url
     * @param params
     * @return
     * @throws Exception
     */
    public static String getReq(String url, Map<String, String> params) throws Exception {

        URI uri = null;
        try {
            List<NameValuePair> valuePairs = new ArrayList<>();
            for (Map.Entry<String, String> mentry : params.entrySet()) {
                valuePairs.add(new BasicNameValuePair(mentry.getKey(), mentry.getValue()));
            }
            uri = new URIBuilder(url).setParameters(valuePairs).build();
        } catch (URISyntaxException e1) {
            e1.printStackTrace();
        }

        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
            HttpGet httpget = new HttpGet(uri);
            CloseableHttpResponse response = httpclient.execute(httpget);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    return EntityUtils.toString(entity);
                }
            } else {
                throw new Exception(String.format("the response status code is %d", statusCode));
            }

        } catch (IOException e) {
            throw new Exception(String.format("the response is error: %s", e.getMessage()));
        }
        return null;
    }

    /**
     * httpclient post 请求封装
     * 
     * @param url
     * @param params
     * @return
     * @throws Exception
     */
    public static String postReq(String url, Map<String, String> params) throws Exception {

        URI uri = null;
        List<NameValuePair> valuePairs = null;
        try {
            valuePairs = new ArrayList<>();
            for (Map.Entry<String, String> mentry : params.entrySet()) {
                valuePairs.add(new BasicNameValuePair(mentry.getKey(), mentry.getValue()));
            }
            uri = new URIBuilder(url).setCharset(Charset.forName("UTF-8")).build();
        } catch (URISyntaxException e1) {
            throw new Exception("the sp url is error");
        }

        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httppost = new HttpPost(uri);
        UrlEncodedFormEntity formEntity;
        try {
            formEntity = new UrlEncodedFormEntity(valuePairs, "UTF-8");
        } catch (UnsupportedEncodingException e1) {
            throw new Exception("the sp url params is error");
        }
        httppost.setEntity(formEntity);
        try {
            CloseableHttpResponse response = httpclient.execute(httppost);
            int statusCode = response.getStatusLine().getStatusCode();

            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    return EntityUtils.toString(entity);

                }
            } else {
                throw new Exception(String.format("the response status code is %d", statusCode));
            }
        } catch (IOException e) {
            throw new Exception(String.format("the response status code is %d", e.getCause()));
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 发送JSON格式的post请求
     * 
     * @param url
     * @param postData
     * @return
     */
    public static String postReq(String url, String postData) {
        HttpPost post = new HttpPost(url);
        String result = "";
        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
            StringEntity reqEntity = new StringEntity(postData, "UTF-8");
            reqEntity.setContentType("application/json");
            post.setEntity(reqEntity);
            HttpResponse res = httpclient.execute(post);
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                result = EntityUtils.toString(res.getEntity()); // 返回json格式
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return result;
    }
}
